package com.pig4cloud.pig.ads.gdt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.ads.gdt.service.GdtAccesstokenService;
import com.pig4cloud.pig.ads.gdt.service.IGdtAdgroupService;
import com.pig4cloud.pig.ads.gdt.service.IGdtCampaignService;
import com.pig4cloud.pig.ads.pig.mapper.gdt.GdtAdgroupMapper;
import com.pig4cloud.pig.api.gdt.dto.FilteringDto;
import com.pig4cloud.pig.api.gdt.dto.GdtAdGroupDeep;
import com.pig4cloud.pig.api.gdt.dto.GdtAdgroupCreateTempDto;
import com.pig4cloud.pig.api.gdt.dto.GdtAdgroupDetail;
import com.pig4cloud.pig.api.gdt.entity.GdtAdgroup;
import com.pig4cloud.pig.common.core.exception.BusinessException;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.api.util.JsonUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 广点通-广告组 服务层实现
 *
 * @author hma
 * @date 2020-12-05
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class GdtAdgroupServiceImpl extends ServiceImpl<GdtAdgroupMapper, GdtAdgroup> implements IGdtAdgroupService {
	@Resource
	private IGdtCampaignService campaignService;

	private final GdtAccesstokenService gdtAccesstokenService;

	private final GdtAdgroupMapper gdtAdgroupMapper;

	@Value(value = "${gdt_url}")
	private String gdtUrl;

	@Value(value = "${gdt_group_create_url}")
	private String gdtGroupCreateUrl;
	@Value(value = "${gdt_adGroup_get_url}")
	private String gdtAdGroupGetUrl;

	@Value(value = "${gdt_group_update_url}")
	private String gdtGroupUpdateUrl;


	//todo  自动版位--------对应特定版位 	siteSets="[\"SITE_SET_MOBILE_UNION\",\"SITE_SET_MOBILE_INNER\",\"SITE_SET_TENCENT_NEWS\",\"SITE_SET_TENCENT_VIDEO\",\"SITE_SET_KANDIAN\",\"SITE_SET_QQ_MUSIC_GAME\"]";
    //todo  三方查询规则  当 operator 为 EQUALS、CONTAINS、LESS_EQUALS、LESS、GREATER_EQUALS、GREATER 时，values数组长度为1； 当 operator 为 IN 时，values数组长度为100；
	/**
	 * 创建广告组--调用三方
	 *
	 * @param gdtAdgroupCreateTempDto
	 * @return
	 */
	@Override
	public GdtAdgroupCreateTempDto createGdtGroup(GdtAdgroupCreateTempDto gdtAdgroupCreateTempDto, List<Long> creativeIdList) {
		try{
			if("1".equals(gdtAdgroupCreateTempDto.getAutomaticSiteEnabled())){
				gdtAdgroupCreateTempDto.setSiteSet(null);
			}
			if("0".equals(gdtAdgroupCreateTempDto.getAppAndroidChannelPackageId())){
				gdtAdgroupCreateTempDto.setAppAndroidChannelPackageId(null);
			}
			String bidMode = gdtAdgroupCreateTempDto.getBidMode();
			if (!("BID_MODE_OCPC").equals(bidMode) && !("BID_MODE_OCPM").equals(bidMode)) {
				gdtAdgroupCreateTempDto.setDeepConversionBehaviorBid(null);
				gdtAdgroupCreateTempDto.setConversionId(null);
			}
			//转换为三方需要的时间格式
			Optional.ofNullable(gdtAdgroupCreateTempDto.getFirstDayBeginTime()).filter(StringUtils::isNotEmpty).filter(p -> gdtAdgroupCreateTempDto.getFirstDayBeginTime().length()==5).ifPresent(p->gdtAdgroupCreateTempDto.setFirstDayBeginTime(p+":00"));
			Map<String,Object> param= JsonUtil.parseJSON2Map(JsonUtil.toUnderlineJSONString(gdtAdgroupCreateTempDto));
			//todo  微信公众账号逻辑  不支持设置，设置该信息会报错
			if(null == param.get("end_date")){
				param.put("end_date","");
			}

			//param.put("conversion_id",5919380);
			//param.put("deep_conversion_behavior_bid",30);
			param.put("automatic_site_enabled","1".equals(gdtAdgroupCreateTempDto.getAutomaticSiteEnabled()));
			if(CollectionUtils.isNotEmpty(creativeIdList)) {
				param.put("dynamic_creative_id_set", creativeIdList.toArray());
			}
			param.remove("optimization_goal");
			param.remove("deep_conversion_spec");
			param.remove("user_action_sets");
			param.remove("auto_enable");
			param.remove("campaign_type");
			param.remove("copy_flag");
			param.remove("id");
			param.remove("launch_date_type");
			param.remove("promoted_object_name");
			param.remove("site_sets");
			param.remove("time_series_type");
			param.remove("user_action_sets_type");
			param.remove("user_id");
			JSONObject jsonObject=campaignService.createOrGetPostThirdResponse(gdtAdgroupCreateTempDto.getAccountId(),"createGdtGroup",gdtGroupCreateUrl,param);
			if(null != jsonObject){
				gdtAdgroupCreateTempDto.setAdgroupId(jsonObject.getLong("adgroup_id"));
			}
			return gdtAdgroupCreateTempDto;
		} catch (Exception e) {
			log.error("createGdtGroup is error", e);
			String messsage=e.getMessage();
			if(StringUtils.isNotBlank(messsage)){
				if(messsage.contains("BusinessException:")){
					String substring0=messsage.substring(0, messsage.indexOf(":"));
					String substring=messsage.substring(substring0.length()+1, messsage.length());
					messsage=substring;
				}
			}else{
				messsage="服务器异常，请稍后重试";
			}
			throw new BusinessException(11,messsage);
		}

	}

	/**
	 * 更新广告组--调用三方
	 *
	 * @param gdtAdgroupCreateTempDto
	 * @return
	 */
	@Override
	public GdtAdgroupCreateTempDto updateGdtGroup(GdtAdgroupCreateTempDto gdtAdgroupCreateTempDto) {
		try{
			if("1".equals(gdtAdgroupCreateTempDto.getAutomaticSiteEnabled())){
				gdtAdgroupCreateTempDto.setSiteSet(null);
			}
			//转换为三方需要的时间格式
			Optional.ofNullable(gdtAdgroupCreateTempDto.getFirstDayBeginTime()).filter(StringUtils::isNotEmpty).ifPresent(p->gdtAdgroupCreateTempDto.setFirstDayBeginTime(p+":00"));
			Map<String,Object> param= JsonUtil.parseJSON2Map(JsonUtil.toUnderlineJSONString(gdtAdgroupCreateTempDto));
			//  微信公众账号逻辑  不支持设置，设置该信息会报错
			if(null == param.get("end_date")){
				param.put("end_date","");
			}
			JSONObject jsonObject=campaignService.createOrGetPostThirdResponse(gdtAdgroupCreateTempDto.getAccountId(),"updateGdtGroup",gdtGroupUpdateUrl,param);
			if(null != jsonObject){
				gdtAdgroupCreateTempDto.setAdgroupId(jsonObject.getLong("adgroup_id"));
			}
			return gdtAdgroupCreateTempDto;
		} catch (Exception e) {
			log.error("updateGdtGroup is error", e);
			String messsage=e.getMessage();
			if(StringUtils.isNotBlank(messsage)){
				if(messsage.contains("BusinessException:")){
					String substring0=messsage.substring(0, messsage.indexOf(":"));
					String substring=messsage.substring(substring0.length()+1, messsage.length());
					messsage=substring;

				}
				if (messsage.contains("投放服务接口错误，请联系我们的专业运营团队，接口错误码为: 305113")){
					messsage = "一条广告仅可使用一次一键起量，你已使用过并关闭，无法再次开启";
				}

			}else{
				messsage="服务器异常，请稍后重试";
			}
			throw new BusinessException(11,messsage);
		}

	}
	/**
	 * 拉取推广计划，并存储数据
	 * @param gdtAdgroupCreateTempDto
     */
	@Override
	public void getGdtGroup(GdtAdgroupCreateTempDto gdtAdgroupCreateTempDto) throws Exception{
		// 拉取广告组存储
		List<FilteringDto> filteringDtos =new ArrayList<>();
		if(null != gdtAdgroupCreateTempDto.getAdgroupId()){
			filteringDtos.add(new FilteringDto("adgroup_id","EQUALS",gdtAdgroupCreateTempDto.getAdgroupId().toString().split(",")));
		}
		String fields = "adgroup_id,adgroup_name,campaign_id,site_set,optimization_goal,billing_event,bid_amount,daily_budget,promoted_object_type,targeting_id,scene_spec,begin_date,end_date,first_day_begin_time,time_series,configured_status,customized_category,created_time,last_modified_time,user_action_sets,is_deleted,cold_start_audience,expand_enabled,expand_targeting,deep_conversion_spec,poi_list,system_status,bid_adjustment,automatic_site_enabled,promoted_object_id,app_android_channel_package_id,targeting,dynamic_creative_id,dynamic_creative_id_set,dynamic_ad_spec,is_rewarded_video_ad,bid_strategy,auto_audience,deep_optimization_action_type,conversion_id,deep_conversion_behavior_bid,deep_conversion_worth_rate,bid_mode,auto_acquisition_enabled,auto_acquisition_budget,auto_derived_creative_enabled,targeting_translation,creative_display_type,status,smart_bid_type" ;
		List<JSONArray> jsonArrayList = campaignService.getThirdResponse(gdtAdgroupCreateTempDto.getAccountId(),"createGdtGroupTemp",gdtAdGroupGetUrl,filteringDtos,null,fields,Boolean.TRUE);
		if(CollectionUtils.isNotEmpty(jsonArrayList)&&CollectionUtils.isNotEmpty(jsonArrayList.get(0))){
			List<Map<String, String>> listMap = JSON.parseObject(jsonArrayList.get(0).toJSONString(), new TypeReference<List<Map<String, String>>>() {});
			GdtAdgroup gdtAdgroup = JsonUtil.toSnakeObject(JSON.toJSONString(listMap.get(0)), GdtAdgroup.class);
			gdtAdgroup.setAccountId(gdtAdgroupCreateTempDto.getAccountId());
			//处理结束日期为空,接口存储空的时候会为1970-01-01
			gdtAdgroup.setEndDate("1970-01-01".equals(gdtAdgroup.getEndDate()) ? "" : gdtAdgroup.getEndDate());

			GdtAdGroupDeep gdtAdGroupDeep = JSON.parseObject(gdtAdgroup.getDeepConversionSpec(),GdtAdGroupDeep.class);
			String goal = null;
			if(gdtAdGroupDeep!=null&&gdtAdGroupDeep.getDeep_conversion_behavior_spec()!=null){
				goal=gdtAdGroupDeep.getDeep_conversion_behavior_spec().getGoal();
			}
			if(goal==null &&gdtAdGroupDeep!=null&&gdtAdGroupDeep.getDeep_conversion_worth_spec()!=null){
				goal=gdtAdGroupDeep.getDeep_conversion_behavior_spec().getGoal();
			}
			if(goal==null && gdtAdGroupDeep!=null&&gdtAdGroupDeep.getDeep_conversion_worth_advanced_spec()!=null){
				goal=gdtAdGroupDeep.getDeep_conversion_behavior_spec().getGoal();
			}
			gdtAdgroup.setDeepOptimizationGoal(goal);

			this.saveOrUpdate(gdtAdgroup);
		}

	}




	/*查询广点通详情：参数 广告组id*/
	@Override
	public R findGdtAdgroupDetailById(GdtAdgroup gdtAdgroup) {

		GdtAdgroupDetail result;
		try {
			result = gdtAdgroupMapper.findGdtAdgroupDetailById(gdtAdgroup);
			//解析
			//1、siteSet
			String siteSet = result.getSiteSet();
			if (StringUtils.isNotBlank(siteSet)){
				String siteSetT = siteSetTransfer(siteSet);
				result.setSiteSet(siteSetT);
			}
			//2、timeSeries  朱仔解析

		} catch (Exception e) {
			e.printStackTrace();
			return R.failed("查询失败");
		}
		return R.ok(result,"查询成功");
	}

	private  static String siteSetTransfer(String siteSet) {
		List<String> siteSetT = Lists.newArrayList();
		if (StringUtils.isBlank(siteSet)){
			return "自动版位";
		}
		List<String> parse = (List<String>)JSONArray.parse(siteSet);
		if (parse.size()<=0){
			return "自动版位";
		}

		for (int i = 0; i < parse.size(); i++) {
			String siteSetValue = GdtAdgroupTempServiceImpl.getSiteSetValue(parse.get(i));
			siteSetT.add(siteSetValue);
		}
		return siteSetT.toString().replace("[","").replace("]","");
	}



}
